using System;
using System.Collections.Generic;
using System.IO;

namespace CoreMobile.csv
{
    public class CSVDocument
    {
        public static string exportData(string[] headers, List<string[]> data, string fileName)
        {
            var document = new CSVDocument();
            document.Headers = headers;
            document.Data = data;

            return document.exportTo(fileName);
        }

        public static string SEPARATOR = ",";

        private List<string[]> data;
        private string[] headers;

        public CSVDocument()
        {
            data=new List<string[]>();
        }

        public string[] Headers
        {
            get { return headers; }
            set { headers = value; }
        }

        public List<string[]> Data
        {
            get { return data; }
            set { data = value; }
        }
    
        public string exportTo(string fileName)
        {
            try
            {
                var writer = new StreamWriter(fileName, false);

                this.writeLine(headers, writer);
                foreach (var row in data)
                    writeLine(row, writer);

                writer.Flush();
                writer.Close();
            }catch(Exception e)
            {
                return e.Message;
            }
            return null;
        }

        private void writeLine(string[] row, StreamWriter writer)
        {
            string line = "";

            foreach (var datum in row) line += SEPARATOR + datum;

            writer.WriteLine(line.Substring(SEPARATOR.Length));
        }
    }
}